#include "wifi_manager.h"
#include "../3party/WakeOnLan.h"

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <IPAddress.h>

/**** 可自定义常量 ****/
#define CONNECTION_RETRY_TIME 50

#define HOST_NAME "open-blitz0"                           // 设备名
static const uint8_t HOST_ADDRESS[4] = {192, 168, 10, 1}; // 页面IP

/**** 全局常量 ****/
static IPAddress apIP(HOST_ADDRESS);
static WiFiUDP gUDP;
static WakeOnLan gWOL(gUDP);

WifiManager::WifiManager() {}

bool WifiManager::setWifiApMode()
{
    // 设置ESP8266设备名
    WiFi.hostname(HOST_NAME);

    // 设置为AP模式
    if (WiFi.getMode() != WIFI_AP)
        WiFi.mode(WIFI_AP);

    // 设置IP和网关
    WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));

    // 返回设置结果
    return WiFi.softAP(HOST_NAME);
}

bool WifiManager::setWifiConnection(const char *ssid, const char *passphrase)
{
    Serial.print("Now connecting to wifi: ");
    Serial.println(ssid);

    // 设置为STA模式
    if (WiFi.getMode() != WIFI_STA)
    {
        Serial.println("Checkout mode sta");
        WiFi.mode(WIFI_STA);
    }

    // 连接wifi
    WiFi.begin(ssid, passphrase);
    for (int i = 0; i < CONNECTION_RETRY_TIME; i++)
    {
        if (WiFi.status() == WL_CONNECTED)
        {
            Serial.println("Wifi has connected!");
            return true;
        }
        Serial.print(".");
        delay(500);
    }
    return false;
}

bool WifiManager::doWol()
{
    if (WiFi.getMode() != WIFI_STA)
    {
        return false;
    }

    // 重复数据包三次,间隔100毫秒
    gWOL.setRepeat(3, 100);
    // 计算广播地址,否则使用255.255.255.255
    gWOL.calculateBroadcastAddress(WiFi.localIP(), WiFi.subnetMask());
    // 发送唤醒包到该地址
    gWOL.sendMagicPacket(m_macaddress);

    Serial.println("Wake on lan succsessful!");
    return true;
}

void WifiManager::setMacAddress(const char *macAddress)
{
    memset(m_macaddress, 0, sizeof(m_macaddress));
    memcpy(m_macaddress, macAddress, sizeof(m_macaddress));
}